import api from '@/services/api';

// 考试相关类型定义
export interface Exam {
  id: number;
  name: string;
  examDate: string;
  subjects: string;
  description?: string;
  status: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED';
  createdAt: string;
  updatedAt: string;
}

// 成绩相关类型定义
export interface Grade {
  id: number;
  examId: number;
  studentId: number;
  subject: string;
  score: number;
  createdAt: string;
  updatedAt: string;
}

export interface StudentGradeDTO {
  studentId: number;
  studentNumber: string;
  name: string;
  score: number | null;
  hasGrade: boolean;
  ranking?: number;
}

export interface StudentExamGradeDTO {
  studentId: number;
  studentNumber: string;
  name: string;
  totalScore: number;
  ranking: number;
  subjectScores: Record<string, number>;
}

export interface ExamGradeDTO {
  examId: number;
  examName: string;
  examDate: string;
  subjects: string[];
  scores: Record<string, number>;
  ranking?: number;
}

export interface PageResponse<T> {
  content: T[];
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
}

// 考试服务
export const examService = {
  // 获取所有考试
  getAllExams: async (): Promise<Exam[]> => {
    try {
      const response = await api.get('/exams');
      return response.data || [];
    } catch (error) {
      console.error('获取所有考试失败:', error);
      throw error;
    }
  },

  // 分页获取考试
  getExamsByPage: async (page: number = 0, size: number = 10): Promise<PageResponse<Exam>> => {
    try {
      const response = await api.get('/exams/page', {
        params: { page, size }
      });
      return response.data;
    } catch (error) {
      console.error('分页获取考试失败:', error);
      throw error;
    }
  },

  // 根据ID获取考试
  getExamById: async (id: number): Promise<Exam> => {
    try {
      const response = await api.get(`/exams/${id}`);
      return response.data;
    } catch (error) {
      console.error(`获取考试(ID: ${id})失败:`, error);
      throw error;
    }
  },

  // 根据名称查找考试
  getExamsByName: async (name: string): Promise<Exam[]> => {
    try {
      const response = await api.get('/exams/by-name', {
        params: { name }
      });
      return response.data || [];
    } catch (error) {
      console.error(`根据名称查找考试失败:`, error);
      throw error;
    }
  },

  // 根据日期查找考试
  getExamsByDate: async (date: string): Promise<Exam[]> => {
    try {
      const response = await api.get('/exams/by-date', {
        params: { date }
      });
      return response.data || [];
    } catch (error) {
      console.error(`根据日期查找考试失败:`, error);
      throw error;
    }
  },

  // 根据日期范围查找考试
  getExamsByDateRange: async (startDate: string, endDate: string): Promise<Exam[]> => {
    try {
      const response = await api.get('/exams/by-date-range', {
        params: { startDate, endDate }
      });
      return response.data || [];
    } catch (error) {
      console.error(`根据日期范围查找考试失败:`, error);
      throw error;
    }
  },

  // 根据科目查找考试
  getExamsBySubject: async (subject: string): Promise<Exam[]> => {
    try {
      const response = await api.get('/exams/by-subject', {
        params: { subject }
      });
      return response.data || [];
    } catch (error) {
      console.error(`根据科目查找考试失败:`, error);
      throw error;
    }
  },

  // 获取考试的科目列表
  getExamSubjects: async (id: number): Promise<string[]> => {
    try {
      const response = await api.get(`/exams/${id}/subjects`);
      return response.data || [];
    } catch (error) {
      console.error(`获取考试科目列表失败:`, error);
      throw error;
    }
  },

  // 创建考试
  createExam: async (exam: Omit<Exam, 'id' | 'createdAt' | 'updatedAt'>): Promise<Exam> => {
    try {
      const response = await api.post('/exams', exam);
      return response.data;
    } catch (error) {
      console.error('创建考试失败:', error);
      throw error;
    }
  },

  // 更新考试
  updateExam: async (id: number, exam: Partial<Exam>): Promise<Exam> => {
    try {
      const response = await api.put(`/exams/${id}`, exam);
      return response.data;
    } catch (error) {
      console.error(`更新考试(ID: ${id})失败:`, error);
      throw error;
    }
  },

  // 删除考试
  deleteExam: async (id: number): Promise<void> => {
    try {
      await api.delete(`/exams/${id}`);
    } catch (error) {
      console.error(`删除考试(ID: ${id})失败:`, error);
      throw error;
    }
  }
};

// 成绩服务
export const gradeService = {
  // 获取考试科目成绩
  getExamSubjectGrades: async (examId: number, subject: string): Promise<StudentGradeDTO[]> => {
    try {
      const response = await api.get(`/grades/exam/${examId}/subject/${subject}`);
      return response.data || [];
    } catch (error) {
      console.error(`获取考试科目成绩失败:`, error);
      throw error;
    }
  },

  // 获取学生考试成绩
  getStudentExamGrades: async (studentId: number, examId: number): Promise<Record<string, number>> => {
    try {
      const response = await api.get(`/grades/student/${studentId}/exam/${examId}`);
      return response.data || {};
    } catch (error) {
      console.error(`获取学生考试成绩失败:`, error);
      throw error;
    }
  },

  // 录入学生成绩
  enterGrade: async (data: { examId: number; subject: string; studentId: number; score: number }): Promise<Grade> => {
    try {
      const response = await api.post('/grades/enter', data);
      return response.data;
    } catch (error) {
      console.error('录入学生成绩失败:', error);
      throw error;
    }
  },

  // 批量录入学生成绩
  batchEnterGrades: async (examId: number, subject: string, scores: Record<number, number>): Promise<Grade[]> => {
    try {
      const response = await api.post('/grades/batch-enter', scores, {
        params: { examId, subject }
      });
      return response.data || [];
    } catch (error) {
      console.error('批量录入学生成绩失败:', error);
      throw error;
    }
  },

  // 获取考试排名
  getExamRanking: async (examId: number): Promise<StudentExamGradeDTO[]> => {
    try {
      const response = await api.get(`/grades/exam/${examId}/ranking`);
      return response.data || [];
    } catch (error) {
      console.error(`获取考试排名失败:`, error);
      throw error;
    }
  },

  // 获取学生历史成绩
  getStudentHistoryGrades: async (studentId: number): Promise<ExamGradeDTO[]> => {
    try {
      const response = await api.get(`/grades/student/${studentId}/history`);
      return response.data || [];
    } catch (error) {
      console.error(`获取学生历史成绩失败:`, error);
      throw error;
    }
  },

  // 获取班级成绩
  getClassGrades: async (params: {
    classId: number;
    subject?: string;
    examId?: number;
    page?: number;
    size?: number;
  }): Promise<PageResponse<Grade>> => {
    try {
      const response = await api.get(`/grades/class/${params.classId}`, {
        params: {
          subject: params.subject,
          examId: params.examId,
          page: params.page || 0,
          size: params.size || 10
        }
      });
      return response.data;
    } catch (error) {
      console.error(`获取班级成绩失败:`, error);
      throw error;
    }
  },

  // 获取成绩列表
  getGrades: async (params: {
    studentId?: number;
    subject?: string;
    examId?: number;
    page?: number;
    size?: number;
  }): Promise<PageResponse<Grade>> => {
    try {
      const response = await api.get('/grades', { params });
      return response.data;
    } catch (error) {
      console.error('获取成绩列表失败:', error);
      throw error;
    }
  },

  // 获取学生成绩（家长角色）
  getStudentGrades: async (studentId: number, params?: {
    subject?: string;
    examId?: number;
  }): Promise<Grade[]> => {
    try {
      const response = await api.get(`/grades/student/${studentId}`, {
        params
      });
      return response.data || [];
    } catch (error) {
      console.error(`获取学生成绩失败:`, error);
      throw error;
    }
  }
};
